<template>
  <div ref="flyBox" class="fly-box" style="background: #333;">
    <!--  viewBox直接可以不写，不写的话其实就是默认等于svg的宽高  -->
    <svg
      :width="width"
      :height="height"
      class="animation-box"
      :viewBox="`0 0 ${width} ${height}`"
    >
      <defs>
        <path
          :id="flyBoxPathId"
          :d="path"
          fill="none"
        ></path>
        <!-- 定义流星发光头部: 静态颜色 -->
        <radialGradient
          :id="radalGradientId"
          cx="50%"
          cy="50%"
          fx="50%"
          fy="50%"
          r="50%"
        >
          <stop offset="0%" stop-color="#fff" stop-opacity="1"></stop>
          <stop offset="100%" stop-color="#fff" stop-opacity="0"></stop>
        </radialGradient>
        <!-- 蒙版 -->
        <mask :id="flyBoxMaskId">
            <circle cx="0" cy="0" r="50" :fill="`url(#${radalGradientId})`">
            <!-- M5 5 L395 5 L395 395 L5 395 Z -->
            <animateMotion
              :dur="`${duration}s`"
              :path="path"
              rotate="auto"
              repeatCount="indefinite"
            ></animateMotion>
          </circle>
        </mask>
      </defs>
      <use
        :href="`#${flyBoxPathId}`"
        stroke-width="1"
        stroke="#235fa7"
      ></use>
      <!--  实际的运动轨迹  -->
      <use
        :href="`#${flyBoxPathId}`"
        stroke-width="3"
        stroke="#4fd2dd"
        :mask="`url(#${flyBoxMaskId})`"
      ></use>
    </svg>
    <div class="fly-box-container">
      <slot></slot>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue';
  import { v4 as uuidv4 } from 'uuid';
  // 定义动画时间
  const props = defineProps({
    duration: {
      type: Number,
      default: 3,
      required: false
    }
  });

  const uuid = uuidv4();
  const width = ref<number>(0);
  const height = ref<number>(0);
  // 组件最外层dom
  const flyBox = ref<HTMLElement | null>(null);
  // 动态计算蒙板运动轨迹
  const path = computed((): string => {
    return `M5 5 L${width.value - 5} 5 L${width.value - 5} ${height.value - 5} L5 ${height.value - 5} Z`
  })
  // 利用uuid为拥有id的dom生成唯一id
  const flyBoxPathId: string = `flyBoxPath-${uuid}`;
  const radalGradientId: string = `radalGradient-${uuid}`;
  const flyBoxMaskId: string = `flyBoxMask-${uuid}`;
  // 挂载后动态获取宽高
  onMounted(() => {
    width.value = flyBox.value!.clientWidth;
    height.value = flyBox.value!.clientHeight;
  });
</script>

<style lang="less" scoped>
  .fly-box {
    margin-top: 15px;
    position: relative;
    width: 100%;
    height: 100%;
    .animation-box {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    .fly-box-container {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      position: relative;
      padding: 10px;
    }
  }
</style>